package com.export.document.service;

import com.export.document.entity.ExportRecord;
import com.export.document.repository.ExportRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReadDBService {
    @Autowired
    private ExportRecordRepository recordRepository;

    public List<ExportRecord> dbTest() {
        return recordRepository.findAll();
    }

    /**
     * 读取数据库表
     *
     * @param shcemaName
     * @return
     */
    public List<Map<String, Object>> readTables(String shcemaName) {
        List<Object[]> list = recordRepository.findTablesByShcemaName(shcemaName);
        List<Map<String, Object>> result = list.stream().map(e -> {
            Map<String, Object> map = new HashMap<>();
            map.put("TABLE_NAME", e[0]);
            return map;
        }).collect(Collectors.toList());
        return result;
    }

    /**
     * 读取表字段
     *
     * @param shcemaName
     * @param tableName
     * @return
     */
    public List<Map<String, Object>> readColumns(String shcemaName, String tableName) {
        List<Object[]> list = recordRepository.findColumnsByTableName(shcemaName, tableName);
        List<Map<String, Object>> result = list.stream().map(e -> {
            Map<String, Object> map = new HashMap<>();
            map.put("TABLE_SCHEMA", e[0]);
            map.put("COLUMN_NAME", e[1]);
            map.put("IS_NULLABLE", e[2]);
            map.put("DATA_TYPE", e[3]);
            map.put("CHARACTER_MAXIMUM_LENGTH", e[4]);
            map.put("NUMERIC_PRECISION", e[5]);
            map.put("NUMERIC_SCALE", e[6]);
            map.put("COLUMN_COMMENT", e[7]);
            return map;
        }).collect(Collectors.toList());
        return result;
    }

    /**
     * 读取数据库
     *
     * @return
     */
    public List<Map<String, Object>> readDB() {
        List<Object[]> list = recordRepository.findDatabase();
        List<Map<String, Object>> result = list.stream().map(e -> {
            Map<String, Object> map = new HashMap<>();
            map.put("SCHEMA_NAME", e[0]);
            return map;
        }).collect(Collectors.toList());
        return result;
    }
}
